<?php

require("config.php");
require_login();
session_start();

if (get_post('postback')) {
	$title = get_post("title");
	$visible = get_post("visible");
	$tags = get_post("tags");
	$content = get_post("content");
	$validate_code = get_post("validate_code");
	
	if ($_SESSION['captcha'] != $validate_code) {
		$t->set_var("T_ERROR", "<p><font color='red'>验证码填的不对！</font></p>");
	} elseif (!$content || strlen($content) < 10) {
		$t->set_var("T_ERROR", "<p><font color='red'>内容总是要写点的！</font></p>");
	} elseif (!in_array($visible, array(1,5,10))) {
		$t->set_var("T_ERROR", "<p><font color='red'>小样机器人，你想干嘛？！</font></p>");
		$visible = 10;
	} else {
		if (!$title) {
			$title = "无题";
		}
		$tags2 = parse_tags($tags);
		$sql = "insert into po_blog (username, title, tags, content, addtime, updatetime, status, visible) values ('%s', '%s', '%s', '%s', now(), now(), 0, '%d')";
		$result = $db->query($sql, $user['username'], $title, implode(",", $tags2), $content, $visible);
		
		if ($result) {
			$id = $db->insert_id();
			$sql2 = "insert into po_tags (tag, unitid, unitname, username, type, status) values ('%s', '%d', '%s', '%s', '%d', 0)";
			foreach ($tags2 as $tag) {
				$db->query($sql2, $tag, $id, $title, $user['username'], TYPE_BLOG);
			}
			$t->set_file("body", "submit_success.html");
			$t->set_var("T_BURL", URL_ROOT . "myblog.php?user=" . $user['username']);
			$t->set_var("T_BTITLE", "我的文章");
			$t->pparse("out", "body");
			exit;
		} else {
			$t->set_var("T_ERROR", "<p><font color='red'>更新数据库失败！</font></p>");
		}
	}
	
	$t->set_var("T_TITLE", $title);
	$t->set_var("T_VISIBLE", $visible);
	$t->set_var("T_TAGS", $tags);
	$t->set_var("T_CONTENT", $content);
} else {
	$t->set_var("T_VISIBLE", 10);
}

page_common("写文章");
$t->set_file("body", "writeblog.html");
$t->pparse("out", "body");